package chances.system.operator.web;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import chances.system.json.JsonResponse;
import chances.system.log.entity.ActionLog;
import chances.system.operator.entity.MgmtInfo;
import chances.system.operator.entity.Oplog;
import chances.system.operator.service.MgmtInfoService;


@RestController
public class MgmtInfoController{

    private static final Logger logger = LoggerFactory.getLogger(MgmtInfoController.class);

	@Autowired
	MgmtInfoService mgmtInfoService;
    
	@ActionLog(operateType=Oplog.OP_EDIT, objName=Oplog.OBJ_TYPE_MGMTINFO, desc="修改站点配置")
    @RequestMapping(path = "/sys/info/save", method = RequestMethod.POST)
	public JsonResponse saveOperator(HttpServletRequest request
	        ,@ModelAttribute  MgmtInfoModel model) {
        JsonResponse jsonResponse = new JsonResponse();
	    MgmtInfo info = model.getMgmtInfo();
	    try {
	        if (info.getId() != null) {
	            MgmtInfo dbInfop = mgmtInfoService.findById(info.getId());
	            if (dbInfop!=null) {
	                info = (MgmtInfo) copyProperties(info, dbInfop);
                }
            }
            mgmtInfoService.saveInfo(info, model.getFaviconFile(), 
                    model.getIconFile(), model.getLogoFile());
            request.setAttribute(Oplog.OBJ_TYPE_MGMTINFO, model.getMgmtInfo());
	    } catch (IOException e) {
	        logger.error(e.toString(), e);
            jsonResponse.setErrorResult(e.getMessage());
            return jsonResponse;
        }
        return jsonResponse;
	}
	
    protected static Object copyProperties(Object src, Object target) {
        BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
        return target;
    }
    
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null)
                emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
